package com.pro.controller;

import com.pro.pojo.JsonData;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YuQing
 * @date 2022/1/23 20:05
 */
@Controller
@RequestMapping("upload")
public class uploadController extends HttpServlet {
    @RequestMapping("/uploadFile")
    @ResponseBody
    public JsonData upload(MultipartFile file, HttpSession session) throws IOException {
        //上传原始文件名
        String name = file.getOriginalFilename();
        String path = null;
        if(file.getSize() > 0) {
            //上传图片存放的路径
            path = System.getProperty("user.dir")+"/src/main/resources/static/upload";
            //封装到一个目录
            File f = new File(path, name);
            //文件上传工具类
            FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("fileName",name);//文件上传的名字
        Map<String, Object> newMap = new HashMap<>();
        newMap.put("url", ""+ name);
        map.put("data", "/upload" + newMap);
        return map != null ? JsonData.buildSuccess(map): JsonData.buildError("服务器出错了");
    }

}
